<template>
  <div class="container">
    <a-card :bordered="false">
      <my-button type='add' @click="open"></my-button>
      <Rtable :total='total' :payload='payload' :list='list' @change='toEdit' @remove='toRemove' @page='pageChange'></Rtable>
    </a-card>
    <!-- 弹窗 -->
    <a-modal :maskClosable="false" :destroyOnClose='true' title="操作" v-model="modal" @ok="submit" :width='600'>
      <a-form :form="form">
        <a-form-item label="角色名" v-bind="formItemLayout">
          <a-input placeholder="请输入角色名" v-decorator="['name',{rules: [{ required: true, message: '请输入角色名' }]}]"></a-input>
        </a-form-item>
        <a-form-item label="角色描述" v-bind="formItemLayout">
          <a-input placeholder="请输入角色描述" v-decorator="['title',{rules: [{ required: true, message: '请输入角色描述' }]}]"></a-input>
        </a-form-item>
        <a-form-item label="能力" v-bind="formItemLayout">
          <a-tree :defaultCheckedKeys='filterAbility' checkable :treeData="perploList" @check='perploCheck' />
        </a-form-item>
        <a-form-item label="菜单权限" v-bind="formItemLayout">
          <a-tree :defaultCheckedKeys='filterMenu' checkable :treeData="routes" @check='routesCheck' />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import Rtable from './table'
import * as Api from '@/api/authManage'
import routes from '@/router/asyncRoutes'

function hasMenu(name, menu) {
  const { alias } = menu.meta || {}
  const menus = alias ? [alias, menu.name] : [menu.name]
  return menus.includes(name)
}

function noChildren(name, data = []) {
  return data.some(item => {
    if (!hasMenu(name, item)) {
      if (!item.children) {
        return false
      } else {
        return noChildren(name, item.children)
      }
    } else {
      return !item.children || item.children.length === 0
    }
  })
}

function noAbility(id, data) {
  return data.some(item => {
    if (item.id != id) {
      if (!item.children) {
        return false
      } else {
        return noAbility(id, item.children)
      }
    } else {
      return !item.children || item.children.length === 0
    }
  })
}

export default {
  components: {
    Rtable
  },
  data() {
    const { page = 1, per_page = 12 } = this.$route.query
    return {
      modal: false,
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        }
      },
      routes,
      form: this.$form.createForm(this),
      list: [],
      record: {
        ability: [],
        menu: []
      },
      payload: {
        page: Number(page),
        per_page: Number(per_page)
      },
      total: 0,
      perploList: []
    };
  },
  computed: {
    filterMenu() {
      const { menu } = this.record
      const { routes = [] } = this
      const filterMenu = menu.filter(name => noChildren(name, routes))
      return filterMenu
    },
    filterAbility() {
      const { ability = [] } = this.record
      const { perploList = [] } = this
      const filterMenu = ability.filter(item => noAbility(item, perploList))
      return filterMenu
    }
  },
  mounted() {
    this.fetchList()
    // 修改routes的值
    this.checkRoutes(this.routes)
  },
  methods: {
    fetchData(payload = {}) {
      this.saveParams(payload)
    },
    pageChange(e) {
      this.payload.page = e.current
      this.fetchData()
    },
    perploCheck(checkedKeys, e) {
      this.record.ability = [...checkedKeys, ...e.halfCheckedKeys]
    },
    routesCheck(checkedKeys, e) {
      this.record.menu = [...checkedKeys, ...e.halfCheckedKeys]
    },
    getRouterName(menu) {
      return (menu.meta && menu.meta.alias) || menu.name
    },
    checkRoutes(routes) {
      routes.map(it => {
        it.title = it.name
        it.key = this.getRouterName(it)
        it.children && this.checkRoutes(it.children)
      })
    },
    checkPeople(routes) {
      routes.map(it => {
        it.key = it.id
        it.children = it.child
        it.children && this.checkPeople(it.children)
      })
    },
    // checkMenu() {
    //   // menu.map(it => {

    //   // })
    // },
    async fetchList() {
      const { list, total } = await Api.roleList(this.payload)
      console.log(list)
      const data = await Api.permissionList()
      this.perploList = data.list
      this.checkPeople(this.perploList)
      this.list = list
      this.total = total
    },
    open() {
      this.modal = true
      this.record = {}
    },
    toEdit(row) {
      this.modal = true
      let d = { ...row }
      d.ability = d.ability.map(it => it.id)
      // this.perploList.filter(it => { this.checkMenu(d.ability) })
      this.record = d
      console.log(row)
      let { name, title } = row
      this.$nextTick(() => {
        this.form.setFieldsValue({
          name, title
        })
      })
    },
    toRemove({ id, name }) {
      this.$confirm({
        title: '删除',
        content: `您确定要删除${name}吗？`,
        onOk: async () => {
          await Api.roleRemove(id)
          this.fetchList()
        }
      })
    },
    // submit
    submit() {
      this.form.validateFields(async (err, data) => {
        if (!err) {
          let d = { ...data }
          let { ability, menu } = this.record
          d.ability_ids = ability.join(",")
          d.menu = JSON.stringify(menu)
          const { id = '' } = this.record
          if (id) {
            d.id = id
            await Api.roleUpdate(d)
          } else {
            await Api.roleAdd(d)
          }
          this.modal = false
          this.fetchList()
        }
      })
    }
  },
}
</script>

<style lang="scss" scoped>
</style>
